package com.one.rope.mvp.web.common.cors;

import com.one.rope.mvp.basecore.util.StringUtils;
import com.one.rope.mvp.web.config.GlobalConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CORSFilter extends CorsFilter {

  public CORSFilter(@Qualifier("mvcHandlerMappingIntrospector") CorsConfigurationSource source) {
    super(source);
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain)
      throws ServletException, IOException {
    if (StringUtils
        .contains(response.getHeader("Access-Control-Allow-Headers"), GlobalConfig.TOKEN_NAME,
            false) == false) {
      response.addHeader("Access-Control-Allow-Headers",
          "Access-Control-Allow-Origin, Origin, Accept, " +
              "X-Requested-With, Content-Type, Access-Control-Request-Method, Cache-Control, Access-Control-Request-Headers, "
              + GlobalConfig.TOKEN_NAME);
    }
    if (StringUtils.isNullOrEmpty(response.getHeader("Access-Control-Allow-Origin"))) {
      response.addHeader("Access-Control-Allow-Origin", "*");
    }
    if (StringUtils.isNullOrEmpty(response.getHeader("Access-Control-Max-Age"))) {
      response.addHeader("Access-Control-Max-Age", "2592000");
    }

    filterChain.doFilter(request, response);
  }

}